let watermark = {}

// configs -- 包含 color 字色 contentSize 字号 
let setWatermark = (str, degree = 15, container, configs) => {
  console.log("-> container", container);
  
  if (!document) {
  	  return false
  }

  let id = 'videoWaterMark';
  
  if (document.getElementById(id) !== null) {
      document.getElementById(id).remove()
  }

  //创建一个画布
  let can = document.createElement('canvas');
  let fontSize = configs.contentSize < 20 ? configs.contentSize : 20
  /**
   * 设置画布的长宽(此时应该根据设置的文字和角度进行设置)
   * 1.长度是cos值
   * 2.高度是sin值
   * 3.斜边就是字数*字号
   * */
  let singleEle = document.createElement('div')
  singleEle.style.fontSize = `${ fontSize }px`
  singleEle.style.position = 'absolute'
  singleEle.innerHTML = str
  document.body.appendChild(singleEle)
  // 以实际长度为准
  let hypotenuse = singleEle.offsetWidth || str.length * fontSize,
  width = hypotenuse * Math.cos(degree * Math.PI / 180) + parseInt(fontSize), 
  height = hypotenuse * Math.sin(degree * Math.PI / 180) + parseInt(fontSize)
  document.body.removeChild(singleEle)
  
  can.width = width < 320 ? 320 : width;
  can.height = height < 108 ? 108 : height;

  let cans = can.getContext('2d');
  //旋转角度
  cans.rotate(-degree * Math.PI / 180);
  cans.font = `${ fontSize }px Arial`;
  //设置填充绘画的颜色、渐变或者模式
  cans.fillStyle = configs.color || 'rgba(255, 255, 255, 0.1)';
  //设置文本内容的当前对齐方式
  cans.textAlign = 'left';
  //设置在绘制文本时使用的当前文本基线
  cans.textBaseline = 'Middle';
  //在画布上绘制填色的文本（输出的文本，开始绘制文本的X坐标位置，开始绘制文本的Y坐标位置）
  cans.fillText(str, 0, can.height );

  let div = document.createElement('div');
  div.id = id;
  div.style.pointerEvents = 'none';
  div.style.top = '0px';
  div.style.left = '0px';
  div.style.position = 'fixed';
  div.style.zIndex = '100000';
  if (container) {
    div.style.width = document.querySelector(container) && (document.querySelector(container).scrollWidth + 'px');
    div.style.height = document.querySelector(container) && (document.querySelector(container).scrollHeight + 'px');
    console.log("-> div.style.height", div.style.height);
  } else {
    div.style.width = document.documentElement.clientWidth + 'px';
    div.style.height = document.documentElement.clientHeight + 'px';
  }
  div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat';
  if (container) {
    document.querySelector(container) && document.querySelector(container).appendChild(div);
  } else {
    document.body.appendChild(div);
  }
  return id;
}

// 该方法只允许调用一次
try {
  watermark.set = (str, degree, container, configs) => {
    let id = setWatermark(str, degree, container, configs);
    let sId = setInterval(() => {
      if (document.getElementById(id) === null) {
        id = setWatermark(str, degree, container, configs);
      } else {
        clearInterval(sId)
      }
    }, 500);
    window.onresize = () => {
      setWatermark(str, degree, container, configs);
    };
  }
} catch (e) { console.log(e) }

export default watermark;
